﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using PocketBook.Model;
using PocketBook.Properties;
using PocketBook.Tasks;
using PocketBook.ViewModels;
using PocketBook.Views;

namespace PocketBook
{
    public class PrintService : IPrintService
    {
        public void Print(Book book)
        {
            var dialog = new PrintDialog();
            if (dialog.ShowDialog() != true) return;

            var document = CreateDocumentFrom(dialog, book);
            if (document == null) return;

            dialog.PrintDocument(document.DocumentPaginator, Resources.Caption_Application);
        }

        public void ShowPrintPreviewOf(Book book)
        {
            var printDialog = new PrintDialog();
#pragma warning disable 168
            var printQueue = printDialog.PrintQueue; // Force initialization
#pragma warning restore 168

            var document = CreateDocumentFrom(printDialog, book);
            if (document == null) return;

            Show.Dialog<PrintPreviewViewModel>()
                .With(dialog => dialog.Document = document)
                .Execute();
        }

        private static IDocumentPaginatorSource CreateDocumentFrom(PrintDialog dialog, Book book)
        {
            var printBounds = new Rect(0, 0, dialog.PrintableAreaWidth, dialog.PrintableAreaHeight);

            var page = new FixedPage
                       {
                           Width = printBounds.Width, 
                           Height = printBounds.Height
                       };

            page.Children.Add(new BookPrintPreview { Source = book });
            page.Measure(printBounds.Size);
            page.Arrange(printBounds);
            page.UpdateLayout();

            var pageContent = new PageContent();
            ((IAddChild)pageContent).AddChild(page);

            var document = new FixedDocument();
            document.DocumentPaginator.PageSize = printBounds.Size;
            document.Pages.Add(pageContent);

            return document;
        }
    }
}